const App = {
    config: Config, // 从 config.js 中导入配置

    init() {
        this.initQuote();
        this.generateNav();
        this.generateSearch();
        this.initTime();
        this.initEvents();
        this.renderAllCards();
        this.initWheelNavigation();
        this.initAbout();
        document.body.classList.add('loaded');
    },

    initQuote() {
        const quoteElement = document.querySelector('.quotes');
        const randomIndex = Math.floor(Math.random() * this.config.quotes.length);
        quoteElement.textContent = this.config.quotes[randomIndex];
    },

    initAbout() {
        const aboutIcon = document.getElementById('aboutIcon');
        const aboutDialog = document.getElementById('aboutDialog');
        const closeDialog = document.getElementById('closeDialog');
        aboutIcon.addEventListener('click', () => {
            aboutDialog.style.display = 'block';
        });
        closeDialog.addEventListener('click', () => {
            aboutDialog.style.display = 'none';
        });
        window.addEventListener('click', (e) => {
            if (e.target === aboutDialog) {
                aboutDialog.style.display = 'none';
            }
        });
    },

    generateNav() {
        const nav = document.querySelector('.nav');
        nav.innerHTML = this.config.navItems.map(item => `
            <div class="nav__item ${item.active ? 'nav__item--active' : ''}" 
                data-target="${item.target}">
                ${item.icon}
                <span>${item.text}</span>
            </div>
        `).join('');
    },

    generateSearch() {
        const searchEngine = document.querySelector('.search-engine');
        const dropdown = document.querySelector('.dropdown');
        const defaultEngine = this.config.searchEngines.find(e => e.default);

        searchEngine.innerHTML = `
            <img src="${defaultEngine.icon}" 
                class="search-engine__icon" 
                alt="${defaultEngine.name}">
            <svg width="24" height="24">
                <path fill="currentColor" d="M7 10l5 5 5-5z"/>
            </svg>
        `;

        dropdown.innerHTML = this.config.searchEngines.map(engine => `
            <div class="dropdown-item" data-engine="${engine.name}">
                <img src="${engine.icon}" alt="${engine.name}">
                <span>${engine.name}</span>
            </div>
        `).join('');
    },

    initTime() {
        const timeHms = document.querySelector('.time-hms');
        const timeDate = document.querySelector('.time-date');

        const updateTime = () => {
            const now = new Date();
            timeHms.textContent = now.toLocaleTimeString('zh-CN', {
                hour12: false,
                hour: '2-digit',
                minute: '2-digit'
            });
            timeDate.innerHTML = now.toLocaleDateString('zh-CN', {
                year: 'numeric',
                month: 'long',
                day: 'numeric'
            }) + '&nbsp;&nbsp;' + now.toLocaleDateString('zh-CN', { weekday: 'long' });
        };

        updateTime();
        setInterval(updateTime, 1000);
    },

    initEvents() {
        // 导航切换
        document.querySelector('.nav').addEventListener('click', e => {
            const item = e.target.closest('.nav__item');
            if (!item) return;

            document.querySelectorAll('.nav__item').forEach(i =>
                i.classList.remove('nav__item--active'));
            item.classList.add('nav__item--active');

            document.querySelectorAll('.content-panel').forEach(panel =>
                panel.classList.remove('content-panel--active'));
            document.getElementById(item.dataset.target)
                .classList.add('content-panel--active');
        });

        // 搜索功能
        const searchEngine = document.querySelector('.search-engine');
        const dropdown = document.querySelector('.dropdown');
        const searchInput = document.querySelector('.search-input');
        const searchButton = document.getElementById('searchButton');

        // 切换搜索引擎
        dropdown.addEventListener('click', e => {
            const item = e.target.closest('.dropdown-item');
            if (!item) return;

            const engine = this.config.searchEngines.find(
                e => e.name === item.dataset.engine
            );

            searchEngine.innerHTML = `
                <img src="${engine.icon}" 
                    class="search-engine__icon" 
                    alt="${engine.name}">
                <svg width="24" height="24">
                    <path fill="currentColor" d="M7 10l5 5 5-5z"/>
                </svg>
            `;

            dropdown.classList.remove('dropdown--visible');
        });

        // 显示/隐藏下拉菜单
        searchEngine.addEventListener('click', () => {
            dropdown.classList.toggle('dropdown--visible');
        });

        document.addEventListener('click', (e) => {
            if (!searchEngine.contains(e.target)) {
                dropdown.classList.remove('dropdown--visible');
            }
        });

        // 搜索功能
        searchInput.addEventListener('keypress', e => {
            if (e.key === 'Enter') this.performSearch();
        });
        searchButton.addEventListener('click', () => this.performSearch());

        // 卡片点击
        document.querySelector('.content').addEventListener('click', e => {
            const card = e.target.closest('.card');
            if (card) window.open(card.dataset.link, '_blank');
        });
    },

    initWheelNavigation() {
        let scrollTimeout;

        window.addEventListener('wheel', e => {
            if (scrollTimeout) return; // 如果正在处理滚动事件，则忽略新的滚动事件

            scrollTimeout = setTimeout(() => {
                scrollTimeout = null; // 重置计时器

                const delta = Math.sign(e.deltaY);
                const currentIndex = Array.from(document.querySelectorAll('.nav__item'))
                    .findIndex(item => item.classList.contains('nav__item--active'));

                const newIndex = (currentIndex + delta + this.config.navItems.length) % this.config.navItems.length;

                document.querySelectorAll('.nav__item')[newIndex].click();
            }, 200); // 设置滚动事件的最小间隔时间（200ms）
        }, { passive: true });
    },

    performSearch() {
        const query = document.querySelector('.search-input').value.trim();
        if (!query) return;

        const engineName = document.querySelector('.search-engine__icon').alt;
        const engine = this.config.searchEngines.find(e => e.name === engineName);
        window.open(engine.url + encodeURIComponent(query), '_blank');
    },

    renderAllCards() {
        const defaultSvgIcon = `
            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" class="card__logo">
                <rect width="24" height="24" fill="#ccc" />
                <circle cx="12" cy="12" r="6" fill="#999" />
            </svg>
        `; // 默认 SVG 图标

        Object.entries(this.config.cards).forEach(([panelId, cards]) => {
            const container = document.getElementById(panelId);
            if (!container) {
                console.error(`未找到 ID 为 ${panelId} 的容器`);
                return;
            }

            container.innerHTML = cards.map(card => {
                let iconContent;

                if (card.icon) {
                    const isInlineSvg = card.icon.trim().startsWith('<svg'); // 判断是否为内联 SVG
                    const isSvgFile = card.icon.trim().endsWith('.svg'); // 判断是否为 SVG 文件路径

                    if (isInlineSvg) {
                        iconContent = card.icon; // 直接使用内联 SVG
                    } else if (isSvgFile) {
                        iconContent = `<img src="${card.icon}" class="card__logo" alt="${card.title || '默认标题'}">`; // 使用 SVG 文件路径
                    } else {
                        iconContent = `<img src="${card.icon}" class="card__logo" alt="${card.title || '默认标题'}">`; // 使用普通图片路径
                    }
                } else {
                    iconContent = defaultSvgIcon; // 如果 icon 为空，使用默认 SVG 图标
                }

                return `
                    <article class="card" data-link="${card.link}">
                        ${iconContent}
                        <div>
                            <h3 class="card__title">${card.title || '未命名卡片'}</h3>
                            <p class="card__desc">${card.desc || '暂无描述'}</p>
                        </div>
                    </article>
                `;
            }).join('');
        });
    }
};

document.addEventListener('DOMContentLoaded', () => App.init());
